package com.example.practical_training_projects.controller;
import com.example.practical_training_projects.util.FileUtil;
import com.example.practical_training_projects.vo.voarticlesandclass;
import com.example.practical_training_projects.entity.articles;
import com.example.practical_training_projects.service.articlesService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("articles")
public class articlesController {
    @Autowired
    private articlesService service;
    /**
     * 返回所有文章信息: http://localhost:8080/articles/list  get请求
     * @return
     */
    @RequestMapping ("list")
    public PageInfo<voarticlesandclass> getAllarticlesandclass(Integer as_uid,String a_title,Integer pageNum,Integer pageSize){
        PageInfo<voarticlesandclass> pageInfo = new PageInfo<>();
       if(as_uid>0){
           pageInfo = service.findarticlesBytitleAndclassuid(as_uid,a_title,pageNum,pageSize);
       }else{
           pageInfo = service.findarticlesBytitle(a_title,pageNum,pageSize);
       }
       return pageInfo;
    }
    //分页
    @GetMapping("/page")
    public PageInfo<voarticlesandclass> getAllclass(Integer pageNum, Integer pageSize){
        PageInfo<voarticlesandclass> pageInfo = service.findclasspage(pageNum,pageSize);
        return pageInfo;
    }

    @GetMapping("/get/{id}")
    public List<articles> getThearticles(@PathVariable("id") Integer a_uid){
        return service.getThearticles(a_uid);
    }
    @GetMapping("/delete/{id}")
    public Integer deletearticlesbyid(@PathVariable("id") Integer a_uid){
        return service.deletearticlesbyid(a_uid);
    }

    @PostMapping("add")
    public  Integer insertarticles(@RequestBody articles art){
        return service.insertarticles(art);
    }
    @PostMapping("update")
    public  Integer updatearticles(@RequestBody articles art){
        return service.updatearticles(art);
    }


    /**
     * 图片上传操作
     * @return
     */
    @PostMapping ("/upload")
    public String getPicFileName(MultipartFile file){
        String oldFileName = file.getOriginalFilename();
        System.out.println(oldFileName);
        String typeName = oldFileName.substring(oldFileName.lastIndexOf('.'));
        String filePath = FileUtil.getUpLoadFilePath();
        System.out.println(typeName);
        String newFileName = System.currentTimeMillis()+typeName;


        try {
            FileUtil.uploadFile(file.getBytes(),filePath,newFileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return newFileName;
    }

@GetMapping("selectauid/{a_title}")
public List<articles> selectauid(@PathVariable String a_title){
        return service.selectauid(a_title);
}

}
